﻿using Sdg.Domain;
using Sdg.Domain.BizObj;
using Sdg.Domain.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Dapper;

namespace SDataGen.Views
{
    /// <summary>
    /// Логика взаимодействия для TablesView.xaml
    /// </summary>
    public partial class TablesView : BaseView, IView
    {
        private Connection _connection;
        private ITableRepository _tableRepository;

        public TablesView()
            :base()
        {
            InitializeComponent();
        }

        public TablesView(ITableRepository tableRepository)
            :this()
        {            
            _tableRepository = tableRepository;
        }

        public new bool Focus()
        {
            ((UIElement)this).Focus();            
            return tablesList.Focus();
        }

        public override void Notify(ViewEventArgs args)
        {
            var conn = args.Params as Connection;

            if (conn != null)
                _connection = conn;
                       

            LoadTables();
        }

        private void LoadTables()
        {
            _tableRepository.SetConnection(_connection.ConnectionString);

            var res = _tableRepository.GetColumns();
            
            tablesList.ItemsSource = GetTableList();
            
        }

        private IEnumerable<TableSettings> GetTableList()
        {
            return _tableRepository.GetDbTables(null);
        }

        private void tablesList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var table = e.AddedItems[0] as TableSettings;
            if (table == null)
                return;

            LoadColumnsFor(table.ObjectId);
        }

        private void LoadColumnsFor(int tableId)
        {
            _tableRepository.GetTableColumns(tableId);
        }
    }
}
